﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

/// <summary>
///LabelMass 的摘要说明
/// </summary>
public class LabelMass
{
    protected enum EnumLabelType
    {
        List, TopUser, UserLogin, SiteNavi, Metakey, MetaDesc, Frindlink,
        History, CorrNews, Sitemap, NorFilt, FlashFilt, Stat, Search, Position, PageTitle, unRule, Detail, ClassList, TodayPic, TodayWord, HistoryIndex, HotTag, CopyRight, SubClass, HotList
    };
    #region 标签参数
    /// <summary>
    /// Loop次数，Loop次数为0或者unLoop标签，为0
    /// </summary>
    protected int Param_Loop;


  

    /// <summary>
    /// 获取到得ID
    /// </summary>
    protected string Param_CurrentNewsID;

    /// <summary>
    /// 会员文章标志
    /// </summary>
    protected string Param_flag;
    /// <summary>
    /// 标签类型
    /// </summary>
    protected EnumLabelType Param_LabelType;
    #endregion 标签参数
    /// <summary>
    /// 标签格式是否有效
    /// </summary>
    protected bool FormatValid = true;
    /// <summary>
    /// 格式非法的说明
    /// </summary>
    protected string InvalidInfo = string.Empty;
    /// <summary>
    /// 标签的主体部份
    /// </summary>
    protected string Mass_Primary = string.Empty;
    /// <summary>
    /// 标签中间插入代码部份
    /// </summary>
    protected string Mass_Inserted = string.Empty;
    /// <summary>
    /// 标签原始内容
    /// </summary>
    protected string Mass_Content = string.Empty;
    /// <summary>
    /// 标签所有参数
    /// </summary>
    protected LabelParameter[] _LblParams = null;
    /// <summary>
    /// 模板类型
    /// </summary>
    protected TempType _TemplateType;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="masscontent">标签的内容</param>
    /// <param name="connection">数据库连接</param>
    /// <param name="currentclassid">当前栏目ID，如果不设置，请赋为null</param>
    /// <param name="currentnewsid">当前新闻ID，如果不设置，请赋为null</param>
    public LabelMass(string masscontent, string currentnewsid, string flag)
    {
        Mass_Content = masscontent;

      

        if (currentnewsid == string.Empty || currentnewsid == null) { Param_CurrentNewsID = null; }
        else { Param_CurrentNewsID = currentnewsid; }

        if (flag == string.Empty || flag == null) { flag = null; }
        else { Param_flag = flag; }

    }
    /// <summary>
    /// 解析标签内容
    /// </summary>
    public void ParseContent()
    {
        int pos1 = Mass_Content.IndexOf(']');
        int pos2 = Mass_Content.LastIndexOf('[');
        if (pos2 < 1)
            throw new Exception("标签格式错误");
        Mass_Primary = Mass_Content.Substring(1, pos1 - 1);
        int n = pos2 - pos1 - 1;
        if (n > 0)
            Mass_Inserted = Mass_Content.Substring(pos1 + 1, n);
        ParsePrimary();
    }
    /// <summary>
    /// 分析标签参数，拆分为数组
    /// </summary>
    private void ParsePrimary()
    {
        if (Mass_Primary.IndexOf(",") > 0)
        {
            string[] _mass_p = Mass_Primary.Split(',');
            if (_mass_p[0].Equals("BMC:Loop"))
                Param_Loop = 1;
            else if (_mass_p[0].Equals("BMC:unLoop"))
                Param_Loop = 0;
            else
            {
                FormatValid = false;
                InvalidInfo = "标签内容不是以[BMC:unLoop或[BMC:Loop开始";
            }
            int n = _mass_p.Length;
            IList<LabelParameter> l = new List<LabelParameter>();
            l.Clear();
            for (int i = 1; i < n; i++)
            {
                if (!FormatValid) break;
                string s = _mass_p[i];
                int pos = s.IndexOf('=');
                if (pos < 0)
                    continue;
                LabelParameter p;
                p.LPName = s.Substring(0, pos).Trim();
                p.LPValue = s.Substring(pos + 1).Trim();
                #region 对标签的必要参数进行一些处理
                switch (p.LPName)
                {
                    case "BMC:Number":
                        if (Param_Loop.Equals(1))
                        {
                            try
                            {
                                Param_Loop = int.Parse(p.LPValue);
                            }
                            catch
                            {
                                FormatValid = false;
                                InvalidInfo = "BMC:Number的值不是有效的数字";
                            }
                        }
                        break;
                    case "BMC:LabelType":
                        try
                        {
                            Param_LabelType = (EnumLabelType)System.Enum.Parse(typeof(EnumLabelType), p.LPValue);
                        }
                        catch
                        {
                            FormatValid = false;
                            InvalidInfo = "BMC:LabelType指定的类型不存在";
                        }
                        break;
                    case "BMC:Root":
                        break;
                    default:
                        AddParameter(p, ref l);
                        break;
                }
                #endregion 对标签的必要参数进行一些处理
            }
            int ln = l.Count;
            if (FormatValid && ln > 0)
            {
                _LblParams = new LabelParameter[ln];
                l.CopyTo(_LblParams, 0);
            }
        }
    }
    /// <summary>
    /// 解析标签生成HTML
    /// </summary>
    /// <returns></returns>
    public string Parse()
    {
        if (!FormatValid)
            return Mass_Content;
        switch (this.Param_LabelType)
        {

            case EnumLabelType.Detail: return this.Analyse_Detail();

            default:
                return string.Empty;
        }
    }

    /// <summary>
    /// 将一个参数加入参数队列
    /// </summary>
    /// <param name="lp">标签参数</param>
    /// <param name="list">列表</param>
    private void AddParameter(LabelParameter lp, ref IList<LabelParameter> list)
    {
        bool flag = true;
        foreach (LabelParameter p in list)
        {
            if (p.LPName.Equals(lp.LPName))
            {
                flag = false;
                break;
            }
        }
        if (flag)
        {
            list.Add(lp);
        }
    }
    /// <summary>
    /// 标签的初始内容
    /// </summary>
    public string Content
    {
        get { return Mass_Content; }
    }
    /// <summary>
    /// 查找某一标签参数的值
    /// </summary>
    /// <param name="ParamName">标签参数的名称</param>
    /// <returns></returns>
    private string GetParamValue(string ParamName)
    {
        string result = string.Empty;
        if (_LblParams == null)
            return null;
        int n = _LblParams.Length;
        for (int i = 0; i < n; i++)
        {
            LabelParameter p = _LblParams[i];
            if (p.LPName.Equals(ParamName))
            {
                result = p.LPValue;
                break;
            }
        }
        return result.Equals(string.Empty) ? null : result;
    }
    /// <summary>
    /// 标签内容格式不正确的说明
    /// </summary>
    public string FormatInvalidMsg
    {
        get { return InvalidInfo; }
    }
    /// <summary>
    /// 设置或获取当前的模板类型
    /// </summary>
    public TempType TemplateType
    {
        set { _TemplateType = value; }
        get { return _TemplateType; }
    }

    /// <summary>
    /// 详细页面[BMC:cPage]a[BMC:cPage]b[BMC:cPage]c[BMC:cPage]d[BMC:cPage]e[BMC:cPage]
    /// </summary>
    /// <returns></returns>
    protected string Analyse_Detail()
    {

        string str = string.Empty;
        string content = this.Mass_Inserted;

        DataSet dsNews = DAL.DBHelper.Query("select * from Tb_Message where id=" + this.Param_CurrentNewsID);
        if (content.IndexOf("[BMC:name]") > 0)
        {
            content = content.Replace("[BMC:name]", dsNews.Tables[0].Rows[0]["name"].ToString());
        }
        if (content.IndexOf("[BMC:tel]") > 0)
        {
            content = content.Replace("[BMC:tel]", dsNews.Tables[0].Rows[0]["tel"].ToString());
        }
        if (content.IndexOf("[BMC:Mtype]") > 0)
        {
            content = content.Replace("[BMC:Mtype]", dsNews.Tables[0].Rows[0]["Mtype"].ToString());
        }
        if (content.IndexOf("[BMC:Mcontent]") > 0)
        {
            content = content.Replace("[BMC:Mcontent]", dsNews.Tables[0].Rows[0]["Mcontent"].ToString());
        }

        if (content.IndexOf("[BMC:Hcontent]") > 0)
        {
            content = content.Replace("[BMC:Hcontent]", dsNews.Tables[0].Rows[0]["Hcontent"].ToString());
        }
        if (content.IndexOf("[BMC:Hname]") > 0)
        {
            content = content.Replace("[BMC:Hname]", dsNews.Tables[0].Rows[0]["Hname"].ToString());
        }
        if (content.IndexOf("[BMC:cPage]") > 0)
        {

        }
        else
        {
            content = content.Replace("[page]", "");
            content = content.Replace("[/page]", "");
        }

        str = content;
        return str;


    }
}
